package com.house.web.controller.system;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.house.common.config.HouseConfig;
import com.house.common.constant.UserConstants;
import com.house.common.core.controller.BaseController;
import com.house.common.core.domain.AjaxResult;
import com.house.common.core.domain.entity.Role;
import com.house.common.core.domain.entity.User;
import com.house.common.core.domain.model.LoginUser;
import com.house.common.core.page.TableDataInfo;
import com.house.common.utils.SecurityUtils;
import com.house.common.utils.StringUtils;
import com.house.common.utils.file.FileUploadUtils;
import com.house.system.service.IRoleService;
import com.house.system.service.IUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 用户Controller
 *
 * @author tc
 * @date 2022-02-04
 */
@RestController
@RequestMapping("/entity/user")
public class UserController extends BaseController {
    @Autowired
    private IUserService userService;

    @Autowired
    private IRoleService roleService;


    /**
     * 查询用户列表
     */
    @PreAuthorize("@ss.hasPermi('entity:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(User user) {
        startPage();
        List<User> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('entity:user:query')")
    @GetMapping(value = {"/{userId}", "/"})
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        AjaxResult ajax = AjaxResult.success();

        User user = userService.selectUserByUserId(userId);
        List<Role> roles = roleService.selectRoleAll();
        ajax.put("roles", roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));

        if (StringUtils.isNotNull(userId)) {
            ajax.put(AjaxResult.DATA_TAG, user);
            ajax.put("roleIds", user.getRoles().stream().map(Role::getRoleId).collect(Collectors.toList()));
        }
        return ajax;
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('entity:user:add')")
    @PostMapping
    public AjaxResult add(@RequestBody User user) {
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('entity:user:edit')")
    @PutMapping
    public AjaxResult edit(@RequestBody User user) {

        User modifyGoal = userService.selectUserByUserId(user.getUserId());

        userService.checkUserAllowed(user);

        if (!user.getPhone().equals(modifyGoal.getPhone()) && StringUtils.isNotEmpty(user.getPhone())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            //当修改用户的电话号码与前端传来的电话号码不相同时再判断是否唯一
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (!user.getEmail().equals(modifyGoal.getEmail()) && StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            //当修改用户的邮箱与前端传来的邮箱相同时再判断是否唯一
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('entity:user:remove')")
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        return toAjax(userService.deleteUserByUserIds(userIds));
    }


    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody User user) {
        userService.checkUserAllowed(user);
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody User user) {
        userService.checkUserAllowed(user);
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.resetPwd(user));
    }


    /**
     * 根据用户编号获取授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping("/authRole/{userId}")
    public AjaxResult authRole(@PathVariable("userId") Long userId)
    {
        AjaxResult ajax = AjaxResult.success();
        User user = userService.selectUserByUserId(userId);
        List<Role> roles = roleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }

    /**
     * 用户授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @PutMapping("/authRole")
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds)
    {
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

}
